package cn.itsource.basic.interceptor;

import cn.itsource.basic.annotation.PreAuthorize;
import cn.itsource.basic.jwt.*;
import cn.itsource.org.domain.Logininfo;
import cn.itsource.system.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class MyInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PermissionMapper permissionMapper;

    @Value("${jwt.rsa.pub}")
    private String jwtRsaPublic;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拿到请求头，判断请求是否存在
        String token = request.getHeader("U-TOKEN");//json web token
        if(token != null){
//            Object loginInfo = redisTemplate.opsForValue().get(token);
            //解密json web token，获取用户基本信息和权限信息
            //获取私钥
            PublicKey publicKey = RsaUtils
                    .getPublicKey(FileCopyUtils
                            .copyToByteArray(this.getClass().getClassLoader().getResourceAsStream(jwtRsaPublic)));
            //解密获取payload对象
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            UserInfo userInfo = payload.getUserInfo();
            Logininfo lf = userInfo.getLogininfo();
            if(lf != null){
                //判断当前用户是否是主站用户，如果是直接放行，不是继续往下执行
                if(lf.getType() != 1){
                    //拿到当前访问的方法（反射）
                    HandlerMethod method = (HandlerMethod) handler;
                    //拿到注解
                    PreAuthorize pre = method.getMethodAnnotation(PreAuthorize.class);
                    //判断注解是否为null，为Null说明不需要校验权限，不为null继续往下校验
                    if(pre != null){
                        //拿到自定义注解的value值
                        String value = pre.value();//dept:deleteById
                        //查询出这个人所拥有的permission
//                        List<String> sns = permissionMapper.querySnByLoginInfoId(lf.getId());
                        List<String> sns = userInfo.getPermissions();
                        //判断这个人拥有的permission中是否包含这个注解的value，
                        if(!sns.contains(value)){
                            response.setCharacterEncoding("utf-8");
                            response.setContentType("application/json;charset=UTF-8");
                            PrintWriter writer = response.getWriter();
                            // 如果包含放行，如果不包含说明没有权限，返回noPermission
                            writer.write("{\"success\":false,\"message\":\"noPermission\"}");
                            writer.flush();
                            writer.close();
                            return false;
                        }
                    }
                   
                }
//                redisTemplate.opsForValue().set(token,loginInfo,30, TimeUnit.MINUTES);
                return true;
            }
        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        return false;
        //从redis查询此token是否存在
        //不存在，返回错误信息
        //存在，刷新过期时间
    }
}
